package org.example.offical.doc;

import dev.langchain4j.community.model.qianfan.QianfanChatModelNameEnum;
import dev.langchain4j.community.model.qianfan.QianfanStreamingChatModel;
import dev.langchain4j.data.message.TextContent;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.request.DefaultChatRequestParameters;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author superMan
 * @since fish_temp_since
 */
@Slf4j
public class StreamingChatLanguageModelDemo {

    public static void main(String[] args) throws InterruptedException {
        // 使用qianfan的api会报错Invalid content-type: application/json
        StreamingChatLanguageModel streamingChatLanguageModel = QianfanStreamingChatModel.builder()
                .apiKey(System.getenv("qianFanApiKey"))
                .secretKey(System.getenv("qianFanApiSecret"))
                .logRequests(true)
                .logResponses(false)
                .temperature(2.0d)
                .modelName(QianfanChatModelNameEnum.ERNIE_BOT_4.getModelName())
                .build();

        ChatRequest chatRequest = ChatRequest.builder()
                .messages(List.of(UserMessage.from(TextContent.from("你好，我叫谢阿花，请使用中文回答我的问题"))))
                .parameters(DefaultChatRequestParameters.builder()
                        .build())
                .build();
        streamingChatLanguageModel.chat(chatRequest, new StreamingChatResponseHandler() {
            @Override
            public void onPartialResponse(String s) {
                System.out.print(s);
            }

            @Override
            public void onCompleteResponse(ChatResponse chatResponse) {
                System.out.println("结束");
                System.out.println(chatResponse.aiMessage().text());
            }

            @Override
            public void onError(Throwable throwable) {
                log.info("异常", throwable);
            }
        });

        TimeUnit.MINUTES.sleep(10L);
    }
}
